import { Modal, Form, Input, DatePicker, TreeSelect, Select, Row, Col, Button, Icon, Radio } from 'antd';
import '@ant-design/compatible/assets/index.css';
import { useState, useEffect, useCallback } from 'react';
import styles from './index.less';

let id = 0;

export default Form.create()(({ form, choiceSupplier, save, onCancel }) => {

  const { getFieldDecorator, validateFields, resetFields, getFieldValue, setFieldsValue } = form;

  const searchFormArr = [
    {
      name: '供应商名称',
      dataIndex: 'supplierName',
      inputType: 'input',
      placeholder: '请输入供应商名称'
    },
    {
      name: '供应商状态',
      dataIndex: 'supplierState',
      inputType: 'radio',
      value: 0,
      radioArr: [
        { name: '启用', value: 0 },
        { name: '停用', value: 1 },
      ]
    },
    {
      name: '结算币种',
      dataIndex: 'currency',
      inputType: 'radio',
      value: '0',
      radioArr: [
        { name: '人民币', value: '0' },
        { name: '美元', value: '1' },
      ]
    }
  ]

  const [supplierEmailArr, setSupplierEmailArr] = useState([]);

  const add = () => {
    setSupplierEmailArr([...supplierEmailArr, ''])
  }

  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 6 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 18 },
    },
  };

  const formItemLayoutWithOutLabel = {
    wrapperCol: {
      xs: { span: 24, offset: 0 },
      sm: { span: 18, offset: 6 },
    },
  };

  const getFields = () => {
    const children = [];
    searchFormArr.forEach((res, idx) => {
      children.push(
        <Col span={24} key={idx}>
          <Form.Item label={res.name} {...formItemLayout}>
            {res.inputType === 'input' && getFieldDecorator(`${res.dataIndex}`, {
              initialValue: res.value,
              rules: [
                {
                  required: true,
                  whitespace: true,
                  message: res.placeholder,
                },
              ],
            })(<Input placeholder={res.placeholder} />)}
            {res.inputType === 'radio' && getFieldDecorator(`${res.dataIndex}`, {
              initialValue: res.value,
            })(
              <Radio.Group>
                {res.radioArr.map(item => <Radio value={item.value}>{item.name}</Radio>)}
              </Radio.Group>
            )}
          </Form.Item>
        </Col>
      );
    })
    getFieldDecorator('supplierEmail', { initialValue: [] });
    return children;
  }

  useEffect(() => {
    if (!choiceSupplier) {
      add();
    } else {
      const emailArr = (choiceSupplier.supplierEmail || '').split(',').map(item => item.slice(0, item.length - 4));
      setSupplierEmailArr(emailArr);
      setFieldsValue({
        supplierName: choiceSupplier.supplierName,
        supplierState: choiceSupplier.supplierState,
        currency: choiceSupplier.currency
      })
    }
  }, [choiceSupplier]);

  const remove = k => {
    const newSupplierEmailArr = JSON.parse(JSON.stringify(getFieldValue('emails')));
    newSupplierEmailArr.splice(k, 1);
    setSupplierEmailArr(newSupplierEmailArr);
    setFieldsValue({
      emails: newSupplierEmailArr
    })
  };

  const formItems = useCallback(() => {
    const itemDom = [];
    (supplierEmailArr || []).map((k, index) => {
      itemDom.push((
        <Form.Item
          {...(index === 0 ? formItemLayout : formItemLayoutWithOutLabel)}
          label={index === 0 ? '供应商邮箱' : ''}
          required={false}
          key={`emails[${index}${k}]`}
        >
          {getFieldDecorator(`emails[${index}]`, {
            validateTrigger: ['onChange', 'onBlur'],
            initialValue: k,
            rules: [
              {
                required: true,
                whitespace: true,
                message: "请输入邮箱.",
              },
              {
                validator: async (rule, value, callback) => {
                  if (value && ((value.indexOf('.com') + 1) || ((value.match(/@/g) || []).length !== 1))) {
                    callback("请输入正确的邮箱");
                  }
                  callback();
                },
              }
            ],
          })(<Input placeholder="请输入邮箱" addonAfter=".com" style={{ width: '90%', marginRight: 8 }} />)}
          {Boolean(index > 0) ? (
            <Icon
              className="dynamic-delete-button"
              type="minus-square-o"
              style={{ fontSize: '26px', verticalAlign: '-0.3em' }}
              onClick={() => remove(index)}
            />
          ) : (<Icon
            className="dynamic-delete-button"
            type="plus-square-o"
            style={{ fontSize: '26px', verticalAlign: '-0.3em' }}
            onClick={() => add()}
          />)}
        </Form.Item>
      ))
    });
    return itemDom;
  }, [supplierEmailArr]);

  const handleSave = () => {
    validateFields((err, values) => {
      // console.log(values);
      if (!err) {
        save(values);
      }
    });
  }

  return (
    <>
      <Form>
        <Row gutter={24}>{getFields()}</Row>
        <div>
          {formItems()}
        </div>
        <div className={styles.modalButton}>
          <Button type="primary" onClick={handleSave}>
            确定
          </Button>
          <Button type="primary" onClick={onCancel}>
            取消
          </Button>
        </div>
      </Form>
    </>
  )
})